package com.example.e_comm.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.e_comm.dto.BaseResp;
import com.example.e_comm.dto.UserCreateReq;
import com.example.e_comm.dto.UserPageReq;
import com.example.e_comm.dto.UserResp;
import com.example.e_comm.entity.User;
import com.example.e_comm.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;

    /**
     * 1 获取所有用户
     */
    @GetMapping("/list")
    public BaseResp<List<UserResp>> listAll() {
        return BaseResp.ok(userService.listAll());
    }

    /**
     * 2 分页用户
     */
    @GetMapping("/page")
    public BaseResp<IPage<UserResp>> pageUsers(UserPageReq req) {
        return BaseResp.ok(userService.pageUsers(req));
    }

    /**
     * 3 根据ID获取用户详情
     */
    @GetMapping("/{id}")
    public BaseResp<UserResp> getById(@PathVariable Long id) {
        return BaseResp.ok(userService.getById(id));
    }

    /**
     * 4 新增用户
     */
    @PostMapping("/create")
    @ResponseStatus(HttpStatus.CREATED)
    public BaseResp<Long> create(@Valid @RequestBody UserCreateReq req) {
        return BaseResp.ok(userService.create(req));
    }

    /**
     * 5 删除用户（逻辑）
     */
    @DeleteMapping("/delete/{id}")
    public BaseResp<Void> delete(@PathVariable Long id) {
        userService.delete(id);
        return BaseResp.ok(null);
    }


    //=================================================================
    @PostMapping("/reqister")
    public ResponseEntity<?> register(@RequestBody User user) {
        try {
            boolean result = userService.register(user);
            if (result) {
                return ResponseEntity.ok("用户注册成功！");
            } else {
                return ResponseEntity.ok("用户注册失败！");
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody String username
            , @RequestParam String password) {
        try {
            String token = userService.login(username, password);
            Map<String, String> response = new HashMap<>();
            response.put("token", token);
            response.put("username", "登陆成功");
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    //当前用户信息
    @GetMapping("/current")
    public ResponseEntity<?> getCurrentUser(@RequestHeader("Authorization") String token) {
        Logger logger = LoggerFactory.getLogger(UserController.class);
        logger.info("当前用户信息：{}", userService.getUserByToken(token));
        try {
            String clean = token.replace("Bearer ", "");
            logger.info("当前用户信息：{}", userService.getUserByToken(clean));

            User user = userService.getUserByToken(clean);
            if (user != null) {
                user.setPassword(null);
                return ResponseEntity.ok(user);
            } else {
                logger.warn("没有找到用户Token");
                return ResponseEntity.status(401).body("没有找到用户Token,或Token已过期");
            }
        } catch (Exception e) {
            logger.warn("请求错误：", e);
            return ResponseEntity.status(400).body("请求错误：" + e.getMessage());
        }
    }


    //退出登录
    @PostMapping("/logout")
    public ResponseEntity<?> logout(@RequestHeader("Authorization") String token) {
        try {
            boolean result = userService.logout(token.replace("Bearer ", ""));
            if (result) {
                return ResponseEntity.ok("用户注销成功！");
            } else {
                return ResponseEntity.ok("用户注销失败！");
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}